<template>
  <div class="app-container">
    <tab-selector
      v-model="currentTabSelector"
      :options="tabSelectorOptions"
      @tab-change="handleTabChange"
    ></tab-selector>

    <el-form inline>
      <el-form-item label="回访时间">
        <date-picker :value="visitTime" @input="handleVisitTime"></date-picker>
      </el-form-item>
      <el-form-item label="完成时间">
        <date-picker
          :value="visitFinishTime"
          @input="handleVisitFinishTime"
        ></date-picker>
      </el-form-item>
      <el-form-item label="创建时间">
        <date-picker
          :value="createTime"
          @input="handleCreateTime"
        ></date-picker>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <columns-filter-button />
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      border
      stripe
      :data="returnList"
      :height="clientHeight"
      :max-height="clientHeight"
      @row-dblclick="handleDetails"
      @cell-click="handleCellClick"
      @filter-change="handleFilterChange"
    >
      <el-table-column type="index" fixed="left"></el-table-column>
      <columns-filter-view>
        <el-table-column
          label="病例号"
          align="center"
          prop="yiyaClinicPerson.caseNumber"
          min-width="120"
        />
      </columns-filter-view>
      <columns-filter-view label="头像">
        <el-table-column
          label="头像"
          align="center"
          prop="imageUrl"
          :min-width="'头像'"
        >
          <avatar-image
            slot-scope="scope"
            :patient="scope.row.yiyaClinicPerson"
          ></avatar-image>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="姓名" align="center" min-width="120">
          <div slot-scope="scope" style="cursor: pointer">
            {{ scope.row.yiyaClinicPerson.name }}
          </div>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="手机号" align="center" min-width="180">
          <hover-phone
            slot-scope="scope"
            :type="1"
            :items="scope.row.yiyaClinicPerson"
          />
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="创建人"
          align="center"
          prop="yiyaVisitTc.createBy"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="回访人员"
          align="center"
          prop="yiyaVisitTc.visitPerson"
          column-key="visitPerson"
          :filters="tcOptions"
          min-width="100"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="跟踪状态"
          align="center"
          prop="trackStatus"
          column-key="trackStatus"
          :filters="trackingStatusOptions"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ trackingStatusEnum[scope.row.yiyaVisitTc.trackStatus] }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="回访内容"
          align="center"
          prop="yiyaVisitTc.contet"
          min-width="180"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="回访结果"
          align="center"
          prop="yiyaVisitTc.result"
          min-width="180"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="回访时间"
          align="center"
          prop="visitTime"
          min-width="180"
        >
          <template slot-scope="scope">
            {{
              dayjs(scope.row.yiyaVisitTc.visitTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          min-width="180"
        >
          <template slot-scope="scope">
            {{
              dayjs(scope.row.yiyaVisitTc.createTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="完成时间"
          align="center"
          prop="visitFinishTime"
          width="180"
        >
          <template slot-scope="scope">
            {{
              scope.row.yiyaVisitTc.visitFinishTime &&
              dayjs(scope.row.yiyaVisitTc.visitFinishTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="回访状态"
          align="center"
          prop="visitStatus"
          :min-width="'到店状态'.length * 30"
        >
          <template slot-scope="scope">
            {{ returnVisitStatusEnum[scope.row.yiyaVisitTc.visitStatus] }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="操作" align="center" min-width="100">
          <el-dropdown slot-scope="scope">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                @click.native="
                  handleReturnVisitEditor(scope.row.yiyaClinicPerson)
                "
              >
                新建回访
              </el-dropdown-item>
              <el-dropdown-item
                v-if="
                  returnVisitStatusEnum[scope.row.yiyaVisitTc.visitStatus] ===
                  '待计划'
                "
                @click.native="
                  handleReturnVisitEditor(
                    scope.row.yiyaClinicPerson,
                    scope.row.yiyaVisitTc
                  )
                "
              >
                编辑回访
              </el-dropdown-item>
              <el-dropdown-item
                v-if="
                  returnVisitStatusEnum[scope.row.yiyaVisitTc.visitStatus] ===
                  '待计划'
                "
                @click.native="handleComplete(scope.row.yiyaVisitTc)"
              >
                完成回访
              </el-dropdown-item>
              <el-dropdown-item
                @click.native="handleDelete(scope.row.yiyaVisitTc)"
              >
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-table-column>
      </columns-filter-view>
      <empty slot="empty"></empty>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    ></pagination>
    <return-visit-editor
      v-model="returnVisitEditor.visible"
      :patient="returnVisitEditor.patient"
      :data="returnVisitEditor.data"
      @ok="getList"
    ></return-visit-editor>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import { listStaff } from '@/api/services/common'
import { delTc, listTcAll, updateTc } from '@/api/services/tc'
import { encode } from '@/utils/utils'
import {
  formatStartWithEnd,
  getThisWeekStartWithEnd,
  getTodayStartWithEnd,
  getTomorrowStartWithEnd,
} from '@/utils/date'
import {
  consumptionStatusOptions,
  returnVisitStatusOptions,
  trackingStatusOptions,
} from '@/utils/options'
import { returnVisitStatusEnum, trackingStatusEnum } from '@/utils/enums'

import TabSelector from '@/components/yiya/TabSelector'
import Empty from '@/components/yiya/Empty'
import TablePhone from '@/components/yiya/TablePhone'
import {
  ColumnsFilterButton,
  ColumnsFilterView,
} from '@/components/yiya/TableColumnsFilter'
import ReturnVisitEditor from './ReturnVisitEditor'
import DatePicker from '@/components/yiya/DatePicker/index'

const QUERY_PARAMS = {
  pageNum: 1,
  pageSize: 50,

  orderByColumn: 'visitTime',
  isAsc: 'desc',

  visitStatus: undefined,
  startVisitTime: undefined,
  endVisitTime: undefined,
  startVisitFinishTime: undefined,
  endVisitFinishTime: undefined,
  startCreateTime: undefined,
  endCreateTime: undefined,
}

export default {
  name: 'TCVisit',
  components: {
    DatePicker,
    TabSelector,
    Empty,
    HoverPhone: () => import('@/components/yiya/hoverPhone'),
    ColumnsFilterButton,
    ColumnsFilterView,
    ReturnVisitEditor,
    AvatarImage: () => import('@/components/yiya/avatarImage'),
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      returnList: [],
      tcList: [],
      queryParams: {},
      currentTabSelector: ' ',
      visitTime: [],
      visitFinishTime: [],
      createTime: [],
      clientHeight: document.body.clientHeight - 325,
      returnVisitEditor: {
        visible: false,
        patient: {},
        data: {},
      },
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
    }),
    dayjs() {
      return dayjs
    },
    trackingStatusOptions() {
      return trackingStatusOptions.map(({ label, value }) => ({
        text: label,
        value,
      }))
    },
    trackingStatusEnum() {
      return trackingStatusEnum
    },
    consumptionStatusOptions() {
      return consumptionStatusOptions.map(({ label, value }) => ({
        text: label,
        value,
      }))
    },
    returnVisitStatusEnum() {
      return returnVisitStatusEnum
    },
    tcOptions() {
      return this.tcList.map(({ userId, userName }) => ({
        text: userName,
        value: userId,
      }))
    },
    tabSelectorOptions() {
      return [
        {
          label: '总数',
          value: ' ',
        },
        ...returnVisitStatusOptions.map(({ label, value }) => ({
          label,
          value: label,
          params: value,
        })),
      ]
    },
  },
  mounted() {
    this.queryParams = {
      ...QUERY_PARAMS,
      ...this.$route.query,
      clinicId: +this.clinicId,
    }
    const today = getTodayStartWithEnd()
    this.handleVisitTime(today)
    this.getTcList()
  },
  methods: {
    async getList() {
      try {
        this.loading = true
        const { rows, total } = await listTcAll(this.queryParams)
        this.returnList = rows
        this.total = total
      } finally {
        this.loading = false
      }
    },
    async getTcList() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: 'TC',
      })
      this.tcList = data
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleDetails(row) {
      const menu = this.$route.path.slice(0, this.$route.path.lastIndexOf('/'))
      this.$router.push(
        `${menu}/details?id=${row.yiyaClinicPerson.id}&redirect=${encode({
          path: this.$route.path,
          query: this.queryParams,
        })}`
      )
    },
    handleCellClick(row, column) {
      if (column.label === '姓名') {
        this.handleDetails(row)
      }
    },
    handleTabChange({ params }) {
      this.queryParams.visitStatus = params
      this.handleQuery()
    },
    handleFilterChange(e) {
      const [key, value] = Object.entries(e)[0]
      this.queryParams[key] = value.join(',')
      this.handleQuery()
    },
    handleVisitTime(e) {
      const { time, start, end } = formatStartWithEnd(e)
      console.log(time, start, end)
      this.visitTime = time
      this.queryParams.startVisitTime = start
      this.queryParams.endVisitTime = end
      this.handleQuery()
    },
    handleCreateTime(e) {
      const { time, start, end } = formatStartWithEnd(e)
      this.createTime = time
      this.queryParams.startCreateTime = start
      this.queryParams.endCreateTime = end
      this.handleQuery()
    },
    handleVisitFinishTime(e) {
      const { time, start, end } = formatStartWithEnd(e)
      this.visitFinishTime = time
      this.queryParams.startVisitFinishTime = start
      this.queryParams.endVisitFinishTime = end
      this.handleQuery()
    },
    handleReturnVisitEditor(patient, visit) {
      this.returnVisitEditor = {
        visible: true,
        patient,
        data: visit || {},
      }
    },
    async handleComplete(visit) {
      const { value: result } = await this.$prompt('回访结果', '完成回访', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入回访结果',
        inputValidator: (e) => !!(e && e.trim()),
        inputErrorMessage: '回访结果不能为空',
      })
      await updateTc({
        id: visit.id,
        result,
        visitStatus: returnVisitStatusEnum['已完成'],
        visitFinishTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      })
      this.msgSuccess('回访完成')
      await this.getList()
    },
    async handleDelete(visit) {
      await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      await delTc(visit.id)
      this.msgSuccess('删除成功')
      await this.getList()
    },
  },
}
</script>

<style lang="scss" scoped>
.content {
  margin-top: -6px;
  height: 20px;
}
</style>
